<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    @ok="saveGroundTodayInfo"
    @close="closeModal"
  >
    <a-form :model="form">
      <a-form-item field="name" label="录入时间">
        <a-date-picker
          style="width: 100%"
          v-model="form.record_time"
          placeholder="请选择录入时间"
        />
      </a-form-item>
      <a-form-item
        field="name"
        :label="item.label"
        v-for="(item, i) in groundFilteredData"
        :key="i"
      >
        <a-input
          style="width: 100%"
          v-model="form[item.dataIndex]"
          :placeholder="`请输入${item.label}地温`"
        />
      </a-form-item> </a-form
  ></a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { saveTempRecord } from '@/api/produce';
import { Message } from '@arco-design/web-vue';

const props = defineProps({
  getGroundTotayInfo: {
    type: Function,
    default: () => {},
  },
});
const visible = ref(false);
const title = ref('地温');
const form = ref({
  id: '',
  workshop_id: '',
  record_time: '',
});
const groundFilteredData = ref([]);
// 打开对话框
const openModal = (ground: any, record: any) => {
  form.value.workshop_id = ground.workshop_id;
  let nowGround = JSON.parse(JSON.stringify(ground));
  const filteredData = nowGround.columns.filter(
    (item) => item.dataIndex !== 'record_time' && item.dataIndex !== 'operate' && item.dataIndex !== 'showRecord_time'
  );
  filteredData.forEach((item, index) => {
    form.value[item.dataIndex] = '';
    groundFilteredData.value.push({
      label: item.title,
      value: form.value[item.dataIndex],
      dataIndex: item.dataIndex,
    });
  });
  if (record && record.id) {
    form.value.id = record.id;
    Object.entries(form.value).forEach(([key, value]) => {
      if (record[key] && record[key] !== '暂未录入') {
        form.value[key] = record[key];
      }
    });
  }
  visible.value = true;
};
const closeModal = () => {
  groundFilteredData.value = [];
  form.value = {
    id: '',
    workshop_id: '',
    record_time: '',
  };
  visible.value = false;
};

const saveGroundTodayInfo = async () => {
  let saveInfo = {
    record_time: form.value.record_time,
    workshop_id: form.value.workshop_id,
    temp_str: '',
  };
  if (form.value.id) {
    saveInfo.id = form.value.id;
  }
  let nowGround = [];
  Object.entries(form.value).forEach(([key, value]) => {
    if (key !== 'workshop_id' && key !== 'record_time' && key !== 'id' && key !== 'showRecord_time') {
      nowGround.push(value);
    }
  });
  saveInfo.temp_str = JSON.stringify(nowGround);
  const { code, message } = await saveTempRecord(saveInfo);
  if (code === 200) {
    props.getGroundTotayInfo();
    Message.success(message);
  }
};

defineExpose({
  openModal,
});
</script>